#include <vector>
#include <queue>

using namespace std;

struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};

class Solution {
public:
    vector<int> rightSideView(TreeNode* root) {
        queue<TreeNode*> queue;
        if (root == nullptr) {
            return {};
        }
        queue.push(root);
        vector<int> output;
        while (queue.size() > 0) {
            int len = queue.size();
            int val = 0;
            for (int i = 0; i < len; i++) {
                TreeNode* node = queue.front();
                queue.pop();
                val = node->val;
                if (node->left != nullptr) {
                    queue.push(node->left);
                }
                if (node->right != nullptr) {
                    queue.push(node->right);
                }
            }
            output.push_back(val);
        }
        return output;
    }
};

